home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / pickle.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  51.3 KB  |  1,413 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. '''Create portable serialized representations of Python objects.
  5.  
  6. See module cPickle for a (much) faster implementation.
  7. See module copy_reg for a mechanism for registering custom picklers.
  8. See module pickletools source for extensive comments.
  9.  
  10. Classes:
  11.  
  12.     Pickler
  13.     Unpickler
  14.  
  15. Functions:
  16.  
  17.     dump(object, file)
  18.     dumps(object) -> string
  19.     load(file) -> object
  20.     loads(string) -> object
  21.  
  22. Misc variables:
  23.  
  24.     __version__
  25.     format_version
  26.     compatible_formats
  27.  
  28. '''
  29. __version__ = '$Revision: 1.156 $'
  30. from types import *
  31. from copy_reg import dispatch_table
  32. from copy_reg import _extension_registry, _inverted_registry, _extension_cache
  33. import marshal
  34. import sys
  35. import struct
  36. import re
  37. import warnings
  38. __all__ = [
  39.     'PickleError',
  40.     'PicklingError',
  41.     'UnpicklingError',
  42.     'Pickler',
  43.     'Unpickler',
  44.     'dump',
  45.     'dumps',
  46.     'load',
  47.     'loads']
  48. format_version = '2.0'
  49. compatible_formats = [
  50.     '1.0',
  51.     '1.1',
  52.     '1.2',
  53.     '1.3',
  54.     '2.0']
  55. HIGHEST_PROTOCOL = 2
  56. mloads = marshal.loads
  57.  
  58. class PickleError(Exception):
  59.     '''A common base class for the other pickling exceptions.'''
  60.     pass
  61.  
  62.  
  63. class PicklingError(PickleError):
  64.     '''This exception is raised when an unpicklable object is passed to the
  65.     dump() method.
  66.  
  67.     '''
  68.     pass
  69.  
  70.  
  71. class UnpicklingError(PickleError):
  72.     '''This exception is raised when there is a problem unpickling an object,
  73.     such as a security violation.
  74.  
  75.     Note that other exceptions may also be raised during unpickling, including
  76.     (but not necessarily limited to) AttributeError, EOFError, ImportError,
  77.     and IndexError.
  78.  
  79.     '''
  80.     pass
  81.  
  82.  
  83. class _Stop(Exception):
  84.     
  85.     def __init__(self, value):
  86.         self.value = value
  87.  
  88.  
  89.  
  90. try:
  91.     from org.python.core import PyStringMap
  92. except ImportError:
  93.     PyStringMap = None
  94.  
  95.  
  96. try:
  97.     UnicodeType
  98. except NameError:
  99.     UnicodeType = None
  100.  
  101. MARK = '('
  102. STOP = '.'
  103. POP = '0'
  104. POP_MARK = '1'
  105. DUP = '2'
  106. FLOAT = 'F'
  107. INT = 'I'
  108. BININT = 'J'
  109. BININT1 = 'K'
  110. LONG = 'L'
  111. BININT2 = 'M'
  112. NONE = 'N'
  113. PERSID = 'P'
  114. BINPERSID = 'Q'
  115. REDUCE = 'R'
  116. STRING = 'S'
  117. BINSTRING = 'T'
  118. SHORT_BINSTRING = 'U'
  119. UNICODE = 'V'
  120. BINUNICODE = 'X'
  121. APPEND = 'a'
  122. BUILD = 'b'
  123. GLOBAL = 'c'
  124. DICT = 'd'
  125. EMPTY_DICT = '}'
  126. APPENDS = 'e'
  127. GET = 'g'
  128. BINGET = 'h'
  129. INST = 'i'
  130. LONG_BINGET = 'j'
  131. LIST = 'l'
  132. EMPTY_LIST = ']'
  133. OBJ = 'o'
  134. PUT = 'p'
  135. BINPUT = 'q'
  136. LONG_BINPUT = 'r'
  137. SETITEM = 's'
  138. TUPLE = 't'
  139. EMPTY_TUPLE = ')'
  140. SETITEMS = 'u'
  141. BINFLOAT = 'G'
  142. TRUE = 'I01\n'
  143. FALSE = 'I00\n'
  144. PROTO = '\x80'
  145. NEWOBJ = '\x81'
  146. EXT1 = '\x82'
  147. EXT2 = '\x83'
  148. EXT4 = '\x84'
  149. TUPLE1 = '\x85'
  150. TUPLE2 = '\x86'
  151. TUPLE3 = '\x87'
  152. NEWTRUE = '\x88'
  153. NEWFALSE = '\x89'
  154. LONG1 = '\x8a'
  155. LONG4 = '\x8b'
  156. _tuplesize2code = [
  157.     EMPTY_TUPLE,
  158.     TUPLE1,
  159.     TUPLE2,
  160.     TUPLE3]
  161. __all__.extend([])
  162. del x
  163.  
  164. class Pickler:
  165.     
  166.     def __init__(self, file, protocol = None, bin = None):
  167.         '''This takes a file-like object for writing a pickle data stream.
  168.  
  169.         The optional protocol argument tells the pickler to use the
  170.         given protocol; supported protocols are 0, 1, 2.  The default
  171.         protocol is 0, to be backwards compatible.  (Protocol 0 is the
  172.         only protocol that can be written to a file opened in text
  173.         mode and read back successfully.  When using a protocol higher
  174.         than 0, make sure the file is opened in binary mode, both when
  175.         pickling and unpickling.)
  176.  
  177.         Protocol 1 is more efficient than protocol 0; protocol 2 is
  178.         more efficient than protocol 1.
  179.  
  180.         Specifying a negative protocol version selects the highest
  181.         protocol version supported.  The higher the protocol used, the
  182.         more recent the version of Python needed to read the pickle
  183.         produced.
  184.  
  185.         The file parameter must have a write() method that accepts a single
  186.         string argument.  It can thus be an open file object, a StringIO
  187.         object, or any other custom object that meets this interface.
  188.  
  189.         '''
  190.         if protocol is not None and bin is not None:
  191.             raise ValueError, "can't specify both 'protocol' and 'bin'"
  192.         
  193.         if bin is not None:
  194.             warnings.warn("The 'bin' argument to Pickler() is deprecated", PendingDeprecationWarning)
  195.             protocol = bin
  196.         
  197.         if protocol is None:
  198.             protocol = 0
  199.         
  200.         if protocol < 0:
  201.             protocol = HIGHEST_PROTOCOL
  202.         elif protocol <= protocol:
  203.             pass
  204.         
  205.         if not (protocol <= HIGHEST_PROTOCOL):
  206.             raise ValueError('pickle protocol must be <= %d' % HIGHEST_PROTOCOL)
  207.         
  208.         self.write = file.write
  209.         self.memo = { }
  210.         self.proto = int(protocol)
  211.         self.bin = protocol >= 1
  212.         self.fast = 0
  213.  
  214.     
  215.     def clear_memo(self):
  216.         '''Clears the pickler\'s "memo".
  217.  
  218.         The memo is the data structure that remembers which objects the
  219.         pickler has already seen, so that shared or recursive objects are
  220.         pickled by reference and not by value.  This method is useful when
  221.         re-using picklers.
  222.  
  223.         '''
  224.         self.memo.clear()
  225.  
  226.     
  227.     def dump(self, obj):
  228.         '''Write a pickled representation of obj to the open file.'''
  229.         if self.proto >= 2:
  230.             self.write(PROTO + chr(self.proto))
  231.         
  232.         self.save(obj)
  233.         self.write(STOP)
  234.  
  235.     
  236.     def memoize(self, obj):
  237.         '''Store an object in the memo.'''
  238.         if self.fast:
  239.             return None
  240.         
  241.         if not id(obj) not in self.memo:
  242.             raise AssertionError
  243.         memo_len = len(self.memo)
  244.         self.write(self.put(memo_len))
  245.         self.memo[id(obj)] = (memo_len, obj)
  246.  
  247.     
  248.     def put(self, i, pack = struct.pack):
  249.         if self.bin:
  250.             if i < 256:
  251.                 return BINPUT + chr(i)
  252.             else:
  253.                 return LONG_BINPUT + pack('<i', i)
  254.         
  255.         return PUT + `i` + '\n'
  256.  
  257.     
  258.     def get(self, i, pack = struct.pack):
  259.         if self.bin:
  260.             if i < 256:
  261.                 return BINGET + chr(i)
  262.             else:
  263.                 return LONG_BINGET + pack('<i', i)
  264.         
  265.         return GET + `i` + '\n'
  266.  
  267.     
  268.     def save(self, obj):
  269.         pid = self.persistent_id(obj)
  270.         if pid:
  271.             self.save_pers(pid)
  272.             return None
  273.         
  274.         x = self.memo.get(id(obj))
  275.         if x:
  276.             self.write(self.get(x[0]))
  277.             return None
  278.         
  279.         t = type(obj)
  280.         f = self.dispatch.get(t)
  281.         if f:
  282.             f(self, obj)
  283.             return None
  284.         
  285.         
  286.         try:
  287.             issc = issubclass(t, TypeType)
  288.         except TypeError:
  289.             issc = 0
  290.  
  291.         if issc:
  292.             self.save_global(obj)
  293.             return None
  294.         
  295.         reduce = dispatch_table.get(t)
  296.         if reduce:
  297.             rv = reduce(obj)
  298.         else:
  299.             reduce = getattr(obj, '__reduce_ex__', None)
  300.             if reduce:
  301.                 rv = reduce(self.proto)
  302.             else:
  303.                 reduce = getattr(obj, '__reduce__', None)
  304.                 if reduce:
  305.                     rv = reduce()
  306.                 else:
  307.                     raise PicklingError("Can't pickle %r object: %r" % (t.__name__, obj))
  308.         if type(rv) is StringType:
  309.             self.save_global(obj, rv)
  310.             return None
  311.         
  312.         if type(rv) is not TupleType:
  313.             raise PicklingError('%s must return string or tuple' % reduce)
  314.         
  315.         l = len(rv)
  316.         if not None if l <= l else l <= 5:
  317.             raise PicklingError('Tuple returned by %s must have two to five elements' % reduce)
  318.         
  319.         self.save_reduce(obj = obj, *rv)
  320.  
  321.     
  322.     def persistent_id(self, obj):
  323.         return None
  324.  
  325.     
  326.     def save_pers(self, pid):
  327.         if self.bin:
  328.             self.save(pid)
  329.             self.write(BINPERSID)
  330.         else:
  331.             self.write(PERSID + str(pid) + '\n')
  332.  
  333.     
  334.     def save_reduce(self, func, args, state = None, listitems = None, dictitems = None, obj = None):
  335.         if not isinstance(args, TupleType):
  336.             if args is None:
  337.                 warnings.warn('__basicnew__ special case is deprecated', DeprecationWarning)
  338.             else:
  339.                 raise PicklingError('args from reduce() should be a tuple')
  340.         
  341.         if not callable(func):
  342.             raise PicklingError('func from reduce should be callable')
  343.         
  344.         save = self.save
  345.         write = self.write
  346.         if self.proto >= 2 and getattr(func, '__name__', '') == '__newobj__':
  347.             cls = args[0]
  348.             if not hasattr(cls, '__new__'):
  349.                 raise PicklingError('args[0] from __newobj__ args has no __new__')
  350.             
  351.             if obj is not None and cls is not obj.__class__:
  352.                 raise PicklingError('args[0] from __newobj__ args has the wrong class')
  353.             
  354.             args = args[1:]
  355.             save(cls)
  356.             save(args)
  357.             write(NEWOBJ)
  358.         else:
  359.             save(func)
  360.             save(args)
  361.             write(REDUCE)
  362.         if obj is not None:
  363.             self.memoize(obj)
  364.         
  365.         if listitems is not None:
  366.             self._batch_appends(listitems)
  367.         
  368.         if dictitems is not None:
  369.             self._batch_setitems(dictitems)
  370.         
  371.         if state is not None:
  372.             save(state)
  373.             write(BUILD)
  374.         
  375.  
  376.     dispatch = { }
  377.     
  378.     def save_none(self, obj):
  379.         self.write(NONE)
  380.  
  381.     dispatch[NoneType] = save_none
  382.     
  383.     def save_bool(self, obj):
  384.         if self.proto >= 2:
  385.             if not obj and NEWTRUE:
  386.                 pass
  387.             self.write(NEWFALSE)
  388.         elif not obj and TRUE:
  389.             pass
  390.         self.write(FALSE)
  391.  
  392.     dispatch[bool] = save_bool
  393.     
  394.     def save_int(self, obj, pack = struct.pack):
  395.         if self.bin:
  396.             if obj >= 0:
  397.                 if obj <= 255:
  398.                     self.write(BININT1 + chr(obj))
  399.                     return None
  400.                 
  401.                 if obj <= 65535:
  402.                     self.write('%c%c%c' % (BININT2, obj & 255, obj >> 8))
  403.                     return None
  404.                 
  405.             
  406.             high_bits = obj >> 31
  407.             if high_bits == 0 or high_bits == -1:
  408.                 self.write(BININT + pack('<i', obj))
  409.                 return None
  410.             
  411.         
  412.         self.write(INT + `obj` + '\n')
  413.  
  414.     dispatch[IntType] = save_int
  415.     
  416.     def save_long(self, obj, pack = struct.pack):
  417.         if self.proto >= 2:
  418.             bytes = encode_long(obj)
  419.             n = len(bytes)
  420.             if n < 256:
  421.                 self.write(LONG1 + chr(n) + bytes)
  422.             else:
  423.                 self.write(LONG4 + pack('<i', n) + bytes)
  424.             return None
  425.         
  426.         self.write(LONG + `obj` + '\n')
  427.  
  428.     dispatch[LongType] = save_long
  429.     
  430.     def save_float(self, obj, pack = struct.pack):
  431.         if self.bin:
  432.             self.write(BINFLOAT + pack('>d', obj))
  433.         else:
  434.             self.write(FLOAT + `obj` + '\n')
  435.  
  436.     dispatch[FloatType] = save_float
  437.     
  438.     def save_string(self, obj, pack = struct.pack):
  439.         if self.bin:
  440.             n = len(obj)
  441.             if n < 256:
  442.                 self.write(SHORT_BINSTRING + chr(n) + obj)
  443.             else:
  444.                 self.write(BINSTRING + pack('<i', n) + obj)
  445.         else:
  446.             self.write(STRING + `obj` + '\n')
  447.         self.memoize(obj)
  448.  
  449.     dispatch[StringType] = save_string
  450.     
  451.     def save_unicode(self, obj, pack = struct.pack):
  452.         if self.bin:
  453.             encoding = obj.encode('utf-8')
  454.             n = len(encoding)
  455.             self.write(BINUNICODE + pack('<i', n) + encoding)
  456.         else:
  457.             obj = obj.replace('\\', '\\u005c')
  458.             obj = obj.replace('\n', '\\u000a')
  459.             self.write(UNICODE + obj.encode('raw-unicode-escape') + '\n')
  460.         self.memoize(obj)
  461.  
  462.     dispatch[UnicodeType] = save_unicode
  463.     if StringType == UnicodeType:
  464.         
  465.         def save_string(self, obj, pack = struct.pack):
  466.             unicode = obj.isunicode()
  467.             if self.bin:
  468.                 if unicode:
  469.                     obj = obj.encode('utf-8')
  470.                 
  471.                 l = len(obj)
  472.                 if l < 256 and not unicode:
  473.                     self.write(SHORT_BINSTRING + chr(l) + obj)
  474.                 else:
  475.                     s = pack('<i', l)
  476.                     if unicode:
  477.                         self.write(BINUNICODE + s + obj)
  478.                     else:
  479.                         self.write(BINSTRING + s + obj)
  480.             elif unicode:
  481.                 obj = obj.replace('\\', '\\u005c')
  482.                 obj = obj.replace('\n', '\\u000a')
  483.                 obj = obj.encode('raw-unicode-escape')
  484.                 self.write(UNICODE + obj + '\n')
  485.             else:
  486.                 self.write(STRING + `obj` + '\n')
  487.             self.memoize(obj)
  488.  
  489.         dispatch[StringType] = save_string
  490.     
  491.     
  492.     def save_tuple(self, obj):
  493.         write = self.write
  494.         proto = self.proto
  495.         n = len(obj)
  496.         if n == 0:
  497.             if proto:
  498.                 write(EMPTY_TUPLE)
  499.             else:
  500.                 write(MARK + TUPLE)
  501.             return None
  502.         
  503.         save = self.save
  504.         memo = self.memo
  505.         if n <= 3 and proto >= 2:
  506.             for element in obj:
  507.                 save(element)
  508.             
  509.             if id(obj) in memo:
  510.                 get = self.get(memo[id(obj)][0])
  511.                 write(POP * n + get)
  512.             else:
  513.                 write(_tuplesize2code[n])
  514.                 self.memoize(obj)
  515.             return None
  516.         
  517.         write(MARK)
  518.         for element in obj:
  519.             save(element)
  520.         
  521.         if id(obj) in memo:
  522.             get = self.get(memo[id(obj)][0])
  523.             if proto:
  524.                 write(POP_MARK + get)
  525.             else:
  526.                 write(POP * (n + 1) + get)
  527.             return None
  528.         
  529.         self.write(TUPLE)
  530.         self.memoize(obj)
  531.  
  532.     dispatch[TupleType] = save_tuple
  533.     
  534.     def save_empty_tuple(self, obj):
  535.         self.write(EMPTY_TUPLE)
  536.  
  537.     
  538.     def save_list(self, obj):
  539.         write = self.write
  540.         if self.bin:
  541.             write(EMPTY_LIST)
  542.         else:
  543.             write(MARK + LIST)
  544.         self.memoize(obj)
  545.         self._batch_appends(iter(obj))
  546.  
  547.     dispatch[ListType] = save_list
  548.     _BATCHSIZE = 1000
  549.     
  550.     def _batch_appends(self, items):
  551.         save = self.save
  552.         write = self.write
  553.         if not (self.bin):
  554.             for x in items:
  555.                 save(x)
  556.                 write(APPEND)
  557.             
  558.             return None
  559.         
  560.         r = xrange(self._BATCHSIZE)
  561.         while items is not None:
  562.             tmp = []
  563.             for i in r:
  564.                 
  565.                 try:
  566.                     x = items.next()
  567.                     tmp.append(x)
  568.                 continue
  569.                 except StopIteration:
  570.                     items = None
  571.                     break
  572.                     continue
  573.                 
  574.  
  575.             
  576.             n = len(tmp)
  577.             if n > 1:
  578.                 write(MARK)
  579.                 for x in tmp:
  580.                     save(x)
  581.                 
  582.                 write(APPENDS)
  583.                 continue
  584.             None<EXCEPTION MATCH>StopIteration
  585.             if n:
  586.                 save(tmp[0])
  587.                 write(APPEND)
  588.                 continue
  589.  
  590.     
  591.     def save_dict(self, obj):
  592.         write = self.write
  593.         if self.bin:
  594.             write(EMPTY_DICT)
  595.         else:
  596.             write(MARK + DICT)
  597.         self.memoize(obj)
  598.         self._batch_setitems(obj.iteritems())
  599.  
  600.     dispatch[DictionaryType] = save_dict
  601.     if not (PyStringMap is None):
  602.         dispatch[PyStringMap] = save_dict
  603.     
  604.     
  605.     def _batch_setitems(self, items):
  606.         save = self.save
  607.         write = self.write
  608.         if not (self.bin):
  609.             for k, v in items:
  610.                 save(k)
  611.                 save(v)
  612.                 write(SETITEM)
  613.             
  614.             return None
  615.         
  616.         r = xrange(self._BATCHSIZE)
  617.         while items is not None:
  618.             tmp = []
  619.             for i in r:
  620.                 
  621.                 try:
  622.                     tmp.append(items.next())
  623.                 continue
  624.                 except StopIteration:
  625.                     items = None
  626.                     break
  627.                     continue
  628.                 
  629.  
  630.             
  631.             n = len(tmp)
  632.             if n > 1:
  633.                 write(MARK)
  634.                 for k, v in tmp:
  635.                     save(k)
  636.                     save(v)
  637.                 
  638.                 write(SETITEMS)
  639.                 continue
  640.             None<EXCEPTION MATCH>StopIteration
  641.             if n:
  642.                 (k, v) = tmp[0]
  643.                 save(k)
  644.                 save(v)
  645.                 write(SETITEM)
  646.                 continue
  647.  
  648.     
  649.     def save_inst(self, obj):
  650.         cls = obj.__class__
  651.         memo = self.memo
  652.         write = self.write
  653.         save = self.save
  654.         if hasattr(obj, '__getinitargs__'):
  655.             args = obj.__getinitargs__()
  656.             len(args)
  657.             _keep_alive(args, memo)
  658.         else:
  659.             args = ()
  660.         write(MARK)
  661.         if self.bin:
  662.             save(cls)
  663.             for arg in args:
  664.                 save(arg)
  665.             
  666.             write(OBJ)
  667.         else:
  668.             for arg in args:
  669.                 save(arg)
  670.             
  671.             write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
  672.         self.memoize(obj)
  673.         
  674.         try:
  675.             getstate = obj.__getstate__
  676.         except AttributeError:
  677.             stuff = obj.__dict__
  678.  
  679.         stuff = getstate()
  680.         _keep_alive(stuff, memo)
  681.         save(stuff)
  682.         write(BUILD)
  683.  
  684.     dispatch[InstanceType] = save_inst
  685.     
  686.     def save_global(self, obj, name = None, pack = struct.pack):
  687.         write = self.write
  688.         memo = self.memo
  689.         if name is None:
  690.             name = obj.__name__
  691.         
  692.         module = getattr(obj, '__module__', None)
  693.         if module is None:
  694.             module = whichmodule(obj, name)
  695.         
  696.         
  697.         try:
  698.             __import__(module)
  699.             mod = sys.modules[module]
  700.             klass = getattr(mod, name)
  701.         except (ImportError, KeyError, AttributeError):
  702.             raise PicklingError("Can't pickle %r: it's not found as %s.%s" % (obj, module, name))
  703.  
  704.         if klass is not obj:
  705.             raise PicklingError("Can't pickle %r: it's not the same object as %s.%s" % (obj, module, name))
  706.         
  707.         if self.proto >= 2:
  708.             code = _extension_registry.get((module, name))
  709.             if code:
  710.                 if not code > 0:
  711.                     raise AssertionError
  712.                 if code <= 255:
  713.                     write(EXT1 + chr(code))
  714.                 elif code <= 65535:
  715.                     write('%c%c%c' % (EXT2, code & 255, code >> 8))
  716.                 else:
  717.                     write(EXT4 + pack('<i', code))
  718.                 return None
  719.             
  720.         
  721.         write(GLOBAL + module + '\n' + name + '\n')
  722.         self.memoize(obj)
  723.  
  724.     dispatch[ClassType] = save_global
  725.     dispatch[FunctionType] = save_global
  726.     dispatch[BuiltinFunctionType] = save_global
  727.     dispatch[TypeType] = save_global
  728.  
  729.  
  730. def _keep_alive(x, memo):
  731.     '''Keeps a reference to the object x in the memo.
  732.  
  733.     Because we remember objects by their id, we have
  734.     to assure that possibly temporary objects are kept
  735.     alive by referencing them.
  736.     We store a reference at the id of the memo, which should
  737.     normally not be used unless someone tries to deepcopy
  738.     the memo itself...
  739.     '''
  740.     
  741.     try:
  742.         memo[id(memo)].append(x)
  743.     except KeyError:
  744.         memo[id(memo)] = [
  745.             x]
  746.  
  747.  
  748. classmap = { }
  749.  
  750. def whichmodule(func, funcname):
  751.     '''Figure out the module in which a function occurs.
  752.  
  753.     Search sys.modules for the module.
  754.     Cache in classmap.
  755.     Return a module name.
  756.     If the function cannot be found, return "__main__".
  757.     '''
  758.     mod = getattr(func, '__module__', None)
  759.     if mod is not None:
  760.         return mod
  761.     
  762.     if func in classmap:
  763.         return classmap[func]
  764.     
  765.     for name, module in sys.modules.items():
  766.         if module is None:
  767.             continue
  768.         
  769.         if name != '__main__' and getattr(module, funcname, None) is func:
  770.             break
  771.             continue
  772.     else:
  773.         name = '__main__'
  774.     classmap[func] = name
  775.     return name
  776.  
  777.  
  778. class Unpickler:
  779.     
  780.     def __init__(self, file):
  781.         '''This takes a file-like object for reading a pickle data stream.
  782.  
  783.         The protocol version of the pickle is detected automatically, so no
  784.         proto argument is needed.
  785.  
  786.         The file-like object must have two methods, a read() method that
  787.         takes an integer argument, and a readline() method that requires no
  788.         arguments.  Both methods should return a string.  Thus file-like
  789.         object can be a file object opened for reading, a StringIO object,
  790.         or any other custom object that meets this interface.
  791.         '''
  792.         self.readline = file.readline
  793.         self.read = file.read
  794.         self.memo = { }
  795.  
  796.     
  797.     def load(self):
  798.         '''Read a pickled object representation from the open file.
  799.  
  800.         Return the reconstituted object hierarchy specified in the file.
  801.         '''
  802.         self.mark = object()
  803.         self.stack = []
  804.         self.append = self.stack.append
  805.         read = self.read
  806.         dispatch = self.dispatch
  807.         
  808.         try:
  809.             while None:
  810.                 pass
  811.             if None:
  812.                 key = read(1)
  813.                 dispatch[key](self)
  814.                 continue
  815.         except _Stop:
  816.             stopinst = None
  817.             return stopinst.value
  818.  
  819.  
  820.     
  821.     def marker(self):
  822.         stack = self.stack
  823.         mark = self.mark
  824.         k = len(stack) - 1
  825.         while stack[k] is not mark:
  826.             k = k - 1
  827.         return k
  828.  
  829.     dispatch = { }
  830.     
  831.     def load_eof(self):
  832.         raise EOFError
  833.  
  834.     dispatch[''] = load_eof
  835.     
  836.     def load_proto(self):
  837.         proto = ord(self.read(1))
  838.         if not None if proto <= proto else proto <= 2:
  839.             raise ValueError, 'unsupported pickle protocol: %d' % proto
  840.         
  841.  
  842.     dispatch[PROTO] = load_proto
  843.     
  844.     def load_persid(self):
  845.         pid = self.readline()[:-1]
  846.         self.append(self.persistent_load(pid))
  847.  
  848.     dispatch[PERSID] = load_persid
  849.     
  850.     def load_binpersid(self):
  851.         pid = self.stack.pop()
  852.         self.append(self.persistent_load(pid))
  853.  
  854.     dispatch[BINPERSID] = load_binpersid
  855.     
  856.     def load_none(self):
  857.         self.append(None)
  858.  
  859.     dispatch[NONE] = load_none
  860.     
  861.     def load_false(self):
  862.         self.append(False)
  863.  
  864.     dispatch[NEWFALSE] = load_false
  865.     
  866.     def load_true(self):
  867.         self.append(True)
  868.  
  869.     dispatch[NEWTRUE] = load_true
  870.     
  871.     def load_int(self):
  872.         data = self.readline()
  873.         if data == FALSE[1:]:
  874.             val = False
  875.         elif data == TRUE[1:]:
  876.             val = True
  877.         else:
  878.             
  879.             try:
  880.                 val = int(data)
  881.             except ValueError:
  882.                 val = long(data)
  883.  
  884.         self.append(val)
  885.  
  886.     dispatch[INT] = load_int
  887.     
  888.     def load_binint(self):
  889.         self.append(mloads('i' + self.read(4)))
  890.  
  891.     dispatch[BININT] = load_binint
  892.     
  893.     def load_binint1(self):
  894.         self.append(ord(self.read(1)))
  895.  
  896.     dispatch[BININT1] = load_binint1
  897.     
  898.     def load_binint2(self):
  899.         self.append(mloads('i' + self.read(2) + '\x00\x00'))
  900.  
  901.     dispatch[BININT2] = load_binint2
  902.     
  903.     def load_long(self):
  904.         self.append(long(self.readline()[:-1], 0))
  905.  
  906.     dispatch[LONG] = load_long
  907.     
  908.     def load_long1(self):
  909.         n = ord(self.read(1))
  910.         bytes = self.read(n)
  911.         self.append(decode_long(bytes))
  912.  
  913.     dispatch[LONG1] = load_long1
  914.     
  915.     def load_long4(self):
  916.         n = mloads('i' + self.read(4))
  917.         bytes = self.read(n)
  918.         self.append(decode_long(bytes))
  919.  
  920.     dispatch[LONG4] = load_long4
  921.     
  922.     def load_float(self):
  923.         self.append(float(self.readline()[:-1]))
  924.  
  925.     dispatch[FLOAT] = load_float
  926.     
  927.     def load_binfloat(self, unpack = struct.unpack):
  928.         self.append(unpack('>d', self.read(8))[0])
  929.  
  930.     dispatch[BINFLOAT] = load_binfloat
  931.     
  932.     def load_string(self):
  933.         rep = self.readline()[:-1]
  934.         for q in '"\'':
  935.             if rep.startswith(q):
  936.                 if not rep.endswith(q):
  937.                     raise ValueError, 'insecure string pickle'
  938.                 
  939.                 rep = rep[len(q):-len(q)]
  940.                 break
  941.                 continue
  942.         else:
  943.             raise ValueError, 'insecure string pickle'
  944.         self.append(rep.decode('string-escape'))
  945.  
  946.     dispatch[STRING] = load_string
  947.     
  948.     def load_binstring(self):
  949.         len = mloads('i' + self.read(4))
  950.         self.append(self.read(len))
  951.  
  952.     dispatch[BINSTRING] = load_binstring
  953.     
  954.     def load_unicode(self):
  955.         self.append(unicode(self.readline()[:-1], 'raw-unicode-escape'))
  956.  
  957.     dispatch[UNICODE] = load_unicode
  958.     
  959.     def load_binunicode(self):
  960.         len = mloads('i' + self.read(4))
  961.         self.append(unicode(self.read(len), 'utf-8'))
  962.  
  963.     dispatch[BINUNICODE] = load_binunicode
  964.     
  965.     def load_short_binstring(self):
  966.         len = ord(self.read(1))
  967.         self.append(self.read(len))
  968.  
  969.     dispatch[SHORT_BINSTRING] = load_short_binstring
  970.     
  971.     def load_tuple(self):
  972.         k = self.marker()
  973.         self.stack[k:] = [
  974.             tuple(self.stack[k + 1:])]
  975.  
  976.     dispatch[TUPLE] = load_tuple
  977.     
  978.     def load_empty_tuple(self):
  979.         self.stack.append(())
  980.  
  981.     dispatch[EMPTY_TUPLE] = load_empty_tuple
  982.     
  983.     def load_tuple1(self):
  984.         self.stack[-1] = (self.stack[-1],)
  985.  
  986.     dispatch[TUPLE1] = load_tuple1
  987.     
  988.     def load_tuple2(self):
  989.         self.stack[-2:] = [
  990.             (self.stack[-2], self.stack[-1])]
  991.  
  992.     dispatch[TUPLE2] = load_tuple2
  993.     
  994.     def load_tuple3(self):
  995.         self.stack[-3:] = [
  996.             (self.stack[-3], self.stack[-2], self.stack[-1])]
  997.  
  998.     dispatch[TUPLE3] = load_tuple3
  999.     
  1000.     def load_empty_list(self):
  1001.         self.stack.append([])
  1002.  
  1003.     dispatch[EMPTY_LIST] = load_empty_list
  1004.     
  1005.     def load_empty_dictionary(self):
  1006.         self.stack.append({ })
  1007.  
  1008.     dispatch[EMPTY_DICT] = load_empty_dictionary
  1009.     
  1010.     def load_list(self):
  1011.         k = self.marker()
  1012.         self.stack[k:] = [
  1013.             self.stack[k + 1:]]
  1014.  
  1015.     dispatch[LIST] = load_list
  1016.     
  1017.     def load_dict(self):
  1018.         k = self.marker()
  1019.         d = { }
  1020.         items = self.stack[k + 1:]
  1021.         for i in range(0, len(items), 2):
  1022.             key = items[i]
  1023.             value = items[i + 1]
  1024.             d[key] = value
  1025.         
  1026.         self.stack[k:] = [
  1027.             d]
  1028.  
  1029.     dispatch[DICT] = load_dict
  1030.     
  1031.     def _instantiate(self, klass, k):
  1032.         args = tuple(self.stack[k + 1:])
  1033.         del self.stack[k:]
  1034.         instantiated = 0
  1035.         if not args and type(klass) is ClassType and not hasattr(klass, '__getinitargs__'):
  1036.             
  1037.             try:
  1038.                 value = _EmptyClass()
  1039.                 value.__class__ = klass
  1040.                 instantiated = 1
  1041.             except RuntimeError:
  1042.                 pass
  1043.             except:
  1044.                 None<EXCEPTION MATCH>RuntimeError
  1045.             
  1046.  
  1047.         None<EXCEPTION MATCH>RuntimeError
  1048.         if not instantiated:
  1049.             
  1050.             try:
  1051.                 value = klass(*args)
  1052.             except TypeError:
  1053.                 err = None
  1054.                 raise TypeError, 'in constructor for %s: %s' % (klass.__name__, str(err)), sys.exc_info()[2]
  1055.             except:
  1056.                 None<EXCEPTION MATCH>TypeError
  1057.             
  1058.  
  1059.         None<EXCEPTION MATCH>TypeError
  1060.         self.append(value)
  1061.  
  1062.     
  1063.     def load_inst(self):
  1064.         module = self.readline()[:-1]
  1065.         name = self.readline()[:-1]
  1066.         klass = self.find_class(module, name)
  1067.         self._instantiate(klass, self.marker())
  1068.  
  1069.     dispatch[INST] = load_inst
  1070.     
  1071.     def load_obj(self):
  1072.         k = self.marker()
  1073.         klass = self.stack.pop(k + 1)
  1074.         self._instantiate(klass, k)
  1075.  
  1076.     dispatch[OBJ] = load_obj
  1077.     
  1078.     def load_newobj(self):
  1079.         args = self.stack.pop()
  1080.         cls = self.stack[-1]
  1081.         obj = cls.__new__(cls, *args)
  1082.         self.stack[-1] = obj
  1083.  
  1084.     dispatch[NEWOBJ] = load_newobj
  1085.     
  1086.     def load_global(self):
  1087.         module = self.readline()[:-1]
  1088.         name = self.readline()[:-1]
  1089.         klass = self.find_class(module, name)
  1090.         self.append(klass)
  1091.  
  1092.     dispatch[GLOBAL] = load_global
  1093.     
  1094.     def load_ext1(self):
  1095.         code = ord(self.read(1))
  1096.         self.get_extension(code)
  1097.  
  1098.     dispatch[EXT1] = load_ext1
  1099.     
  1100.     def load_ext2(self):
  1101.         code = mloads('i' + self.read(2) + '\x00\x00')
  1102.         self.get_extension(code)
  1103.  
  1104.     dispatch[EXT2] = load_ext2
  1105.     
  1106.     def load_ext4(self):
  1107.         code = mloads('i' + self.read(4))
  1108.         self.get_extension(code)
  1109.  
  1110.     dispatch[EXT4] = load_ext4
  1111.     
  1112.     def get_extension(self, code):
  1113.         nil = []
  1114.         obj = _extension_cache.get(code, nil)
  1115.         if obj is not nil:
  1116.             self.append(obj)
  1117.             return None
  1118.         
  1119.         key = _inverted_registry.get(code)
  1120.         if not key:
  1121.             raise ValueError('unregistered extension code %d' % code)
  1122.         
  1123.         obj = self.find_class(*key)
  1124.         _extension_cache[code] = obj
  1125.         self.append(obj)
  1126.  
  1127.     
  1128.     def find_class(self, module, name):
  1129.         __import__(module)
  1130.         mod = sys.modules[module]
  1131.         klass = getattr(mod, name)
  1132.         return klass
  1133.  
  1134.     
  1135.     def load_reduce(self):
  1136.         stack = self.stack
  1137.         args = stack.pop()
  1138.         func = stack[-1]
  1139.         if args is None:
  1140.             warnings.warn('__basicnew__ special case is deprecated', DeprecationWarning)
  1141.             value = func.__basicnew__()
  1142.         else:
  1143.             value = func(*args)
  1144.         stack[-1] = value
  1145.  
  1146.     dispatch[REDUCE] = load_reduce
  1147.     
  1148.     def load_pop(self):
  1149.         del self.stack[-1]
  1150.  
  1151.     dispatch[POP] = load_pop
  1152.     
  1153.     def load_pop_mark(self):
  1154.         k = self.marker()
  1155.         del self.stack[k:]
  1156.  
  1157.     dispatch[POP_MARK] = load_pop_mark
  1158.     
  1159.     def load_dup(self):
  1160.         self.append(self.stack[-1])
  1161.  
  1162.     dispatch[DUP] = load_dup
  1163.     
  1164.     def load_get(self):
  1165.         self.append(self.memo[self.readline()[:-1]])
  1166.  
  1167.     dispatch[GET] = load_get
  1168.     
  1169.     def load_binget(self):
  1170.         i = ord(self.read(1))
  1171.         self.append(self.memo[`i`])
  1172.  
  1173.     dispatch[BINGET] = load_binget
  1174.     
  1175.     def load_long_binget(self):
  1176.         i = mloads('i' + self.read(4))
  1177.         self.append(self.memo[`i`])
  1178.  
  1179.     dispatch[LONG_BINGET] = load_long_binget
  1180.     
  1181.     def load_put(self):
  1182.         self.memo[self.readline()[:-1]] = self.stack[-1]
  1183.  
  1184.     dispatch[PUT] = load_put
  1185.     
  1186.     def load_binput(self):
  1187.         i = ord(self.read(1))
  1188.         self.memo[`i`] = self.stack[-1]
  1189.  
  1190.     dispatch[BINPUT] = load_binput
  1191.     
  1192.     def load_long_binput(self):
  1193.         i = mloads('i' + self.read(4))
  1194.         self.memo[`i`] = self.stack[-1]
  1195.  
  1196.     dispatch[LONG_BINPUT] = load_long_binput
  1197.     
  1198.     def load_append(self):
  1199.         stack = self.stack
  1200.         value = stack.pop()
  1201.         list = stack[-1]
  1202.         list.append(value)
  1203.  
  1204.     dispatch[APPEND] = load_append
  1205.     
  1206.     def load_appends(self):
  1207.         stack = self.stack
  1208.         mark = self.marker()
  1209.         list = stack[mark - 1]
  1210.         list.extend(stack[mark + 1:])
  1211.         del stack[mark:]
  1212.  
  1213.     dispatch[APPENDS] = load_appends
  1214.     
  1215.     def load_setitem(self):
  1216.         stack = self.stack
  1217.         value = stack.pop()
  1218.         key = stack.pop()
  1219.         dict = stack[-1]
  1220.         dict[key] = value
  1221.  
  1222.     dispatch[SETITEM] = load_setitem
  1223.     
  1224.     def load_setitems(self):
  1225.         stack = self.stack
  1226.         mark = self.marker()
  1227.         dict = stack[mark - 1]
  1228.         for i in range(mark + 1, len(stack), 2):
  1229.             dict[stack[i]] = stack[i + 1]
  1230.         
  1231.         del stack[mark:]
  1232.  
  1233.     dispatch[SETITEMS] = load_setitems
  1234.     
  1235.     def load_build(self):
  1236.         stack = self.stack
  1237.         state = stack.pop()
  1238.         inst = stack[-1]
  1239.         setstate = getattr(inst, '__setstate__', None)
  1240.         if setstate:
  1241.             setstate(state)
  1242.             return None
  1243.         
  1244.         slotstate = None
  1245.         if isinstance(state, tuple) and len(state) == 2:
  1246.             (state, slotstate) = state
  1247.         
  1248.         if state:
  1249.             
  1250.             try:
  1251.                 inst.__dict__.update(state)
  1252.             except RuntimeError:
  1253.                 for k, v in state.items():
  1254.                     setattr(inst, k, v)
  1255.                 
  1256.             
  1257.  
  1258.         None<EXCEPTION MATCH>RuntimeError
  1259.         if slotstate:
  1260.             for k, v in slotstate.items():
  1261.                 setattr(inst, k, v)
  1262.             
  1263.         
  1264.  
  1265.     dispatch[BUILD] = load_build
  1266.     
  1267.     def load_mark(self):
  1268.         self.append(self.mark)
  1269.  
  1270.     dispatch[MARK] = load_mark
  1271.     
  1272.     def load_stop(self):
  1273.         value = self.stack.pop()
  1274.         raise _Stop(value)
  1275.  
  1276.     dispatch[STOP] = load_stop
  1277.  
  1278.  
  1279. class _EmptyClass:
  1280.     pass
  1281.  
  1282. import binascii as _binascii
  1283.  
  1284. def encode_long(x):
  1285.     """Encode a long to a two's complement little-endian binary string.
  1286.     Note that 0L is a special case, returning an empty string, to save a
  1287.     byte in the LONG1 pickling context.
  1288.  
  1289.     >>> encode_long(0L)
  1290.     ''
  1291.     >>> encode_long(255L)
  1292.     '\\xff\\x00'
  1293.     >>> encode_long(32767L)
  1294.     '\\xff\\x7f'
  1295.     >>> encode_long(-256L)
  1296.     '\\x00\\xff'
  1297.     >>> encode_long(-32768L)
  1298.     '\\x00\\x80'
  1299.     >>> encode_long(-128L)
  1300.     '\\x80'
  1301.     >>> encode_long(127L)
  1302.     '\\x7f'
  1303.     >>>
  1304.     """
  1305.     if x == 0:
  1306.         return ''
  1307.     
  1308.     if x > 0:
  1309.         ashex = hex(x)
  1310.         if not ashex.startswith('0x'):
  1311.             raise AssertionError
  1312.         njunkchars = 2 + ashex.endswith('L')
  1313.         nibbles = len(ashex) - njunkchars
  1314.         if nibbles & 1:
  1315.             ashex = '0x0' + ashex[2:]
  1316.         elif int(ashex[2], 16) >= 8:
  1317.             ashex = '0x00' + ashex[2:]
  1318.         
  1319.     else:
  1320.         ashex = hex(-x)
  1321.         if not ashex.startswith('0x'):
  1322.             raise AssertionError
  1323.         njunkchars = 2 + ashex.endswith('L')
  1324.         nibbles = len(ashex) - njunkchars
  1325.         if nibbles & 1:
  1326.             nibbles += 1
  1327.         
  1328.         nbits = nibbles * 4
  1329.         x += 0x1L << nbits
  1330.         if not x > 0:
  1331.             raise AssertionError
  1332.         ashex = hex(x)
  1333.         njunkchars = 2 + ashex.endswith('L')
  1334.         newnibbles = len(ashex) - njunkchars
  1335.         if newnibbles < nibbles:
  1336.             ashex = '0x' + '0' * (nibbles - newnibbles) + ashex[2:]
  1337.         
  1338.         if int(ashex[2], 16) < 8:
  1339.             ashex = '0xff' + ashex[2:]
  1340.         
  1341.     if ashex.endswith('L'):
  1342.         ashex = ashex[2:-1]
  1343.     else:
  1344.         ashex = ashex[2:]
  1345.     if not len(ashex) & 1 == 0:
  1346.         raise AssertionError, (x, ashex)
  1347.     binary = _binascii.unhexlify(ashex)
  1348.     return binary[::-1]
  1349.  
  1350.  
  1351. def decode_long(data):
  1352.     '''Decode a long from a two\'s complement little-endian binary string.
  1353.  
  1354.     >>> decode_long(\'\')
  1355.     0L
  1356.     >>> decode_long("\\xff\\x00")
  1357.     255L
  1358.     >>> decode_long("\\xff\\x7f")
  1359.     32767L
  1360.     >>> decode_long("\\x00\\xff")
  1361.     -256L
  1362.     >>> decode_long("\\x00\\x80")
  1363.     -32768L
  1364.     >>> decode_long("\\x80")
  1365.     -128L
  1366.     >>> decode_long("\\x7f")
  1367.     127L
  1368.     '''
  1369.     nbytes = len(data)
  1370.     if nbytes == 0:
  1371.         return 0x0L
  1372.     
  1373.     ashex = _binascii.hexlify(data[::-1])
  1374.     n = long(ashex, 16)
  1375.     if data[-1] >= '\x80':
  1376.         n -= 0x1L << nbytes * 8
  1377.     
  1378.     return n
  1379.  
  1380.  
  1381. try:
  1382.     from cStringIO import StringIO
  1383. except ImportError:
  1384.     from StringIO import StringIO
  1385.  
  1386.  
  1387. def dump(obj, file, protocol = None, bin = None):
  1388.     Pickler(file, protocol, bin).dump(obj)
  1389.  
  1390.  
  1391. def dumps(obj, protocol = None, bin = None):
  1392.     file = StringIO()
  1393.     Pickler(file, protocol, bin).dump(obj)
  1394.     return file.getvalue()
  1395.  
  1396.  
  1397. def load(file):
  1398.     return Unpickler(file).load()
  1399.  
  1400.  
  1401. def loads(str):
  1402.     file = StringIO(str)
  1403.     return Unpickler(file).load()
  1404.  
  1405.  
  1406. def _test():
  1407.     import doctest
  1408.     return doctest.testmod()
  1409.  
  1410. if __name__ == '__main__':
  1411.     _test()
  1412.  
  1413.